const userModel = require('../model/user');
const {sign} = require('./auth')

async function addUser(req, res, next) {
    try {
        const {
            username,
            phone,
            avatar,
            sex,
            address,
            birthday,
            password,
            serialNum,
            competence,
            position,
            workStatus
        } = req.body;

        await userModel.create({
            username,
            phone,
            avatar,
            sex,
            address,
            birthday,
            password,
            serialNum,
            competence: [],
            position, // 职位
            workStatus
        })
        res.json({
            code: 200,
            msg: '用户新建成功'
        })
    } catch (err){
        next(err);
    }
}

async function login (req, res, next) {
    try {
        const {phone, password} = req.body;
        const user = await userModel.findOne({
            phone
        })
        if (user&&user.password === password) {
            const token = sign({userId: user._id})
            res.json({
                code: 200,
                data: {
                    token
                },
                msg: '登录成功！'
            })
        } else if(user) {
            res.json({
                code: 400,
                msg: '密码不正确'
            })
        } else {
            res.json({
                code: 400,
                msg: '该用户不存在'
            })
        }
    } catch(err) {
        next(err)
    }
}

async function getUserByToken (req, res, next) {
    try {
        const {userId} = req.user;
        const userData = await userModel.findById(userId).select('-password');
        res.json({
            code: 200,
            data: userData
        })
    } catch(err) {
        next(err)
    }
}

module.exports = {
    addUser,
    login,
    getUserByToken
}
